import 'dart:async';
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import 'package:go_router/go_router.dart';

import '../../managers/chapter_manager.dart';
import '../../utils/http_helper.dart';
import '../../utils/user_manager.dart';
import '../../widgets/login_dialog.dart';
import '../../widgets/purchase_bottom_sheet.dart';
import '../home/home_detail_screen.dart';
import '../widget/chapter_list_sheet.dart';
import '../widget/image_list_view.dart';
import '../widget/reader_controls.dart';

class ComicReaderPage extends StatefulWidget {
  final String initialChapterId;
  final String selectedChapterId;

  const ComicReaderPage({
    super.key,
    required this.initialChapterId,
    required this.selectedChapterId,
  });

  @override
  State<ComicReaderPage> createState() => _ComicReaderPageState();
}

class _ComicReaderPageState extends State<ComicReaderPage> {
  static const String _logTag = '[漫画阅读器]';

  final ItemScrollController itemScrollController = ItemScrollController();
  final ScrollOffsetController scrollOffsetController =
      ScrollOffsetController();
  final ItemPositionsListener itemPositionsListener =
      ItemPositionsListener.create();
  final ChapterManager chapterManager = ChapterManager();

  // 位置监听器函数引用
  void Function()? _currentPositionListener;

  int _visibleImageIndex = 0;
  bool _isLoadingNext = false;
  bool _isInitializing = true;
  bool _showControls = true;
  bool _isSliderDragging = false;
  double _sliderValue = 1.0;

  // 自动阅读相关
  bool _isAutoReading = false;
  Timer? _autoScrollTimer;

  @override
  void initState() {
    super.initState();
    print(
        '$_logTag initState 开始初始化阅读器，初始_isSliderDragging: $_isSliderDragging');
    _initializeData();
  }

  @override
  void dispose() {
    print('$_logTag dispose 销毁阅读器，清理资源');
    _autoScrollTimer?.cancel();
    if (_currentPositionListener != null) {
      itemPositionsListener.itemPositions
          .removeListener(_currentPositionListener!);
    }
    super.dispose();
  }

  Future<void> _initializeData() async {
    print(
        '$_logTag _initializeData 开始初始化数据，chapterId: ${widget.initialChapterId}');
    setState(() => _isInitializing = true);
    try {
      print('$_logTag _initializeData 开始加载漫画详情');
      await chapterManager.loadComicDetail(
          widget.initialChapterId, widget.selectedChapterId);
      print(
          '$_logTag _initializeData 漫画详情加载完成，章节数: ${chapterManager.chapters.length}');

      print(
          '$_logTag _initializeData 开始加载当前章节，索引: ${chapterManager.currentChapterIndex}');
      final (success, code) = await chapterManager
          .loadSingleChapter(chapterManager.currentChapterIndex);
      if (!success) {
        print('$_logTag _initializeData 当前章节加载失败，尝试加载下一章节');
        await _loadNextChapter();
      } else {
        print(
            '$_logTag _initializeData 当前章节加载成功，图片数量: ${chapterManager.allImages.length}');
      }

      print('$_logTag _initializeData 设置位置监听器');
      _setupPositionListener();
    } catch (e) {
      print('$_logTag _initializeData 初始化错误: $e');
    } finally {
      setState(() => _isInitializing = false);
      print('$_logTag _initializeData 初始化完成');
    }
  }

  Future<void> _loadNextChapter() async {
    if (_isLoadingNext) {
      print('$_logTag _loadNextChapter 正在加载下一章，跳过重复请求');
      return;
    }

    print(
        '$_logTag _loadNextChapter 开始加载下一章，当前章节索引: ${chapterManager.displayChapterIndex}');
    setState(() => _isLoadingNext = true);
    final success = await chapterManager.loadNextChapter();
    print(
        '$_logTag _loadNextChapter 下一章加载${success ? '成功' : '失败'}，总图片数: ${chapterManager.allImages.length}');
    setState(() => _isLoadingNext = false);
  }

  Future<void> _onRefresh() async {
    print('$_logTag _onRefresh 开始下拉刷新加载上一章，当前可见图片索引: $_visibleImageIndex');
    final success =
        await chapterManager.loadPreviousChapter(_visibleImageIndex);
    print('$_logTag _onRefresh 上一章加载${success ? '成功' : '失败'}');
    if (success) {
      final newIndex =
          _visibleImageIndex + chapterManager.chapterImageCounts[0];
      print('$_logTag _onRefresh 更新可见图片索引: $_visibleImageIndex -> $newIndex');
      setState(() {
        _visibleImageIndex = newIndex;
      });
    }
  }

  void _setupPositionListener() {
    print('$_logTag _setupPositionListener 设置位置监听器');

    // 移除旧的监听器
    if (_currentPositionListener != null) {
      print('$_logTag _setupPositionListener 移除旧的位置监听器');
      itemPositionsListener.itemPositions
          .removeListener(_currentPositionListener!);
      _currentPositionListener = null;
    }

    // 创建新的监听器回调函数
    void positionListener() {
      if (_isSliderDragging) {
        return;
      }

      final positions = itemPositionsListener.itemPositions.value;
      if (positions.isEmpty) return;

      final visibleItems = positions
          .where((p) => p.itemLeadingEdge < 1 && p.itemTrailingEdge > 0);
      if (visibleItems.isEmpty) return;

      ItemPosition? bestItem;
      for (final item in visibleItems) {
        if (item.itemLeadingEdge <= 0.2) {
          if (bestItem == null ||
              item.itemLeadingEdge < bestItem.itemLeadingEdge) {
            bestItem = item;
          }
        }
      }

      bestItem ??= visibleItems.reduce((a, b) =>
          (a.itemTrailingEdge - a.itemLeadingEdge) >
                  (b.itemTrailingEdge - b.itemLeadingEdge)
              ? a
              : b);

      final newIndex = bestItem.index;
      final maxIndex =
          positions.map((p) => p.index).reduce((a, b) => a > b ? a : b);

      if (newIndex != _visibleImageIndex &&
          newIndex < chapterManager.allImages.length) {
        final chapterIndex =
            chapterManager.findChapterIndexFromImageIndex(newIndex);
        print(
            '$_logTag positionListener 滑动到新图片，索引: $_visibleImageIndex -> $newIndex，章节: $chapterIndex');
        setState(() {
          _visibleImageIndex = newIndex;
          chapterManager.updateDisplayChapterIndex(chapterIndex);
        });
      }

      final triggerThreshold = chapterManager.allImages.length - 3;
      if (maxIndex >= triggerThreshold) {
        print(
            '$_logTag positionListener 滑动到底部，触发自动加载下一章，maxIndex: $maxIndex，总图片数: ${chapterManager.allImages.length}');
        // _loadNextChapter();
      }
    }

    // 保存监听器引用并添加
    _currentPositionListener = positionListener;
    itemPositionsListener.itemPositions.addListener(_currentPositionListener!);
    print(
        '$_logTag _setupPositionListener 位置监听器设置完成，当前图片数量: ${chapterManager.allImages.length}');
  }

  void _goToPreviousChapter() {
    print(
        '$_logTag _goToPreviousChapter 点击上一章按钮，当前章节: ${chapterManager.displayChapterIndex}');
    if (_isAutoReading) {
      print('$_logTag _goToPreviousChapter 停止自动阅读');
      _toggleAutoReading();
    }
    if (chapterManager.displayChapterIndex > 0) {
      final targetIndex = chapterManager.displayChapterIndex - 1;
      print('$_logTag _goToPreviousChapter 跳转到上一章，目标章节: $targetIndex');
      _loadSingleChapter(targetIndex);
    } else {
      print('$_logTag _goToPreviousChapter 已经是第一章，无法跳转');
    }
  }

  Future<void> _goToNextChapter() async {
    print(
        '$_logTag _goToNextChapter 点击下一章按钮，当前章节: ${chapterManager.displayChapterIndex}');
    if (_isAutoReading) {
      print('$_logTag _goToNextChapter 停止自动阅读');
      _toggleAutoReading();
    }
    if (chapterManager.displayChapterIndex <
        chapterManager.chapters.length - 1) {
      final targetIndex = chapterManager.displayChapterIndex + 1;
      final chapter = chapterManager.chapters[targetIndex];
      if (chapter.isBuy == false) {
        print('$_logTag _goToNextChapter 跳转到下一章，目标章节: $targetIndex');
        _loadSingleChapter(targetIndex);
      } else {
        final isLoggedIn = await UserManager.isLoggedIn();
        if (isLoggedIn) {
          PurchaseBottomSheet.show(
            context,
            chapterTitle: chapter.chapterTitle ?? "Chapter ${targetIndex + 1}",
            chapterPrice: chapterManager.comicDetail?.buyPrice?.chapterPrice ??
                50, // Replace with actual chapter price
            comicPrice: chapterManager.comicDetail?.buyPrice?.comicPrice ??
                200, // Replace with actual comic price
            comicTitle:
                chapterManager.comicDetail?.comic?.title ?? "This Comic",
            onPurchaseChapter: () async {
              // Handle chapter purchase
              print('🔥🔥🔥 onPurchaseChapter 被调用了！');
              // Handle chapter purchase
              print('Purchase chapter: ${chapter.chapterId}');
              // Add your chapter purchase logic here
              EasyLoading.show();
              try {
                print('🚀 准备发送HTTP请求...');
                final response = await HttpUtil().postJson(
                  'ComicMember/BuyComic',
                  data: {"id": chapter.chapterId, "isAllBuyChapter": false},
                );
                print("✅ 购买章节接口返回: $response");
                EasyLoading.dismiss();
                if (response?['status'] == 200) {
                  EasyLoading.showToast("Purchase completed successfully");
                  // ref
                  //     .read(comicDetailProvider(comicId)
                  //         .notifier)
                  // .refresh();
                  _loadSingleChapter(targetIndex);
                } else {
                  if (response?['status'] == 400) {
                    _showBalanceInsufficientDialog(context);
                  } else {
                    EasyLoading.showToast(response?['message']);
                  }
                }
              } catch (e) {
                print('❌ 购买请求异常: $e');
                EasyLoading.dismiss();
                EasyLoading.showToast("Purchase failed: $e");
              }
            },
            onPurchaseComic: () async {
              EasyLoading.show();
              try {
                print('🚀 准备发送HTTP请求...');
                final response = await HttpUtil().postJson(
                  'ComicMember/BuyComic',
                  data: {
                    "id": chapterManager.comicDetail?.comic?.id ?? '',
                    "isAllBuyChapter": true
                  },
                );
                print("✅ 购买章节接口返回: $response");
                EasyLoading.dismiss();
                if (response?['status'] == 200) {
                  EasyLoading.showToast("Purchase completed successfully");
                  _loadSingleChapter(targetIndex);
                } else {
                  if (response?['status'] == 400) {
                    _showBalanceInsufficientDialog(context);
                  } else {
                    EasyLoading.showToast(response?['message']);
                  }
                }
              } catch (e) {
                print('❌ 购买请求异常: $e');
                EasyLoading.dismiss();
                EasyLoading.showToast("Purchase failed: $e");
              }
            },
            onSubscribePremium: () {
              _loadSingleChapter(targetIndex);
            },
          );
        } else {
          showDialog(
            context: context,
            barrierDismissible: false,
            builder: (context) => const LoginDialog(),
          );
        }
      }
    } else {
      EasyLoading.showToast("You have reached the last chapter.");
    }
  }

  Future<void> _loadSingleChapter(int chapterIndex) async {
    print('$_logTag _loadSingleChapter 开始加载单个章节，章节索引: $chapterIndex');
    setState(() => _isInitializing = true);
    final (success, code) =
        await chapterManager.loadSingleChapter(chapterIndex);
    print(
        '$_logTag _loadSingleChapter 章节加载${success ? '成功' : '失败'}，图片数量: ${success ? chapterManager.allImages.length : 0}');
    if (success) {
      setState(() {
        _visibleImageIndex = 0;
        _isInitializing = false;
        // 切换章节时，清理所有可能干扰的状态
        _isSliderDragging = false;
        // 隐藏操作栏，避免进度条干扰
        _showControls = false;
      });
      print('$_logTag _loadSingleChapter 状态重置完成，跳转到第一张图片');
      _jumpToImageInstant(0);

      // 延迟一小段时间后显示操作栏，确保跳转完成
      Future.delayed(const Duration(milliseconds: 500), () {
        if (mounted) {
          setState(() {
            _showControls = true;
          });
          print('$_logTag _loadSingleChapter 延迟显示操作栏');
        }
      });
    } else {
      setState(() => _isInitializing = false);
      print('$_logTag _loadSingleChapter 章节内容为空，显示错误消息');
      if (code == 1000) {
        final chapter = chapterManager.chapters[chapterIndex];
        final isLoggedIn = await UserManager.isLoggedIn();
        if (isLoggedIn) {
          PurchaseBottomSheet.show(
            context,
            chapterTitle: chapter.chapterTitle ?? "Chapter ${chapterIndex + 1}",
            chapterPrice: chapterManager.comicDetail?.buyPrice?.chapterPrice ??
                50, // Replace with actual chapter price
            comicPrice: chapterManager.comicDetail?.buyPrice?.comicPrice ??
                200, // Replace with actual comic price
            comicTitle:
                chapterManager.comicDetail?.comic?.title ?? "This Comic",
            onPurchaseChapter: () async {
              // Handle chapter purchase
              print('🔥🔥🔥 onPurchaseChapter 被调用了！');
              // Handle chapter purchase
              print('Purchase chapter: ${chapter.chapterId}');
              // Add your chapter purchase logic here
              EasyLoading.show();
              try {
                print('🚀 准备发送HTTP请求...');
                final response = await HttpUtil().postJson(
                  'ComicMember/BuyComic',
                  data: {"id": chapter.chapterId, "isAllBuyChapter": false},
                );
                print("✅ 购买章节接口返回: $response");
                EasyLoading.dismiss();
                if (response?['status'] == 200) {
                  EasyLoading.showToast("Purchase completed successfully");
                  // ref
                  //     .read(comicDetailProvider(comicId)
                  //         .notifier)
                  // .refresh();
                  _loadSingleChapter(chapterIndex);
                } else {
                  if (response?['status'] == 400) {
                    _showBalanceInsufficientDialog(context);
                  } else {
                    EasyLoading.showToast(response?['message']);
                  }
                }
              } catch (e) {
                print('❌ 购买请求异常: $e');
                EasyLoading.dismiss();
                EasyLoading.showToast("Purchase failed: $e");
              }
            },
            onPurchaseComic: () async {
              EasyLoading.show();
              try {
                print('🚀 准备发送HTTP请求...');
                final response = await HttpUtil().postJson(
                  'ComicMember/BuyComic',
                  data: {
                    "id": chapterManager.comicDetail?.comic?.id ?? '',
                    "isAllBuyChapter": true
                  },
                );
                print("✅ 购买章节接口返回: $response");
                EasyLoading.dismiss();
                if (response?['status'] == 200) {
                  EasyLoading.showToast("Purchase completed successfully");
                  _loadSingleChapter(chapterIndex);
                } else {
                  if (response?['status'] == 400) {
                    _showBalanceInsufficientDialog(context);
                  } else {
                    EasyLoading.showToast(response?['message']);
                  }
                }
              } catch (e) {
                print('❌ 购买请求异常: $e');
                EasyLoading.dismiss();
                EasyLoading.showToast("Purchase failed: $e");
              }
            },
            onSubscribePremium: () {
              _loadSingleChapter(chapterIndex);
            },
          );
        } else {
          showDialog(
            context: context,
            barrierDismissible: false,
            builder: (context) => const LoginDialog(),
          );
        }
      } else {
        _showErrorMessage('Chapter content is empty');
      }
    }
  }

  void _jumpToImageInCurrentChapterInstant(int imageNumberInChapter) {
    final targetIndex = chapterManager.calculateGlobalIndex(
        imageNumberInChapter, _visibleImageIndex);
    print(
        '$_logTag _jumpToImageInCurrentChapterInstant 计算全局索引，章节内图片: $imageNumberInChapter，目标索引: $targetIndex');
    if (targetIndex != -1) {
      _jumpToImageInstant(targetIndex);
    } else {
      print('$_logTag _jumpToImageInCurrentChapterInstant 无效的目标索引');
    }
  }

  void _jumpToImageInstant(int globalImageIndex) {
    if (globalImageIndex < 0 ||
        globalImageIndex >= chapterManager.allImages.length) {
      print(
          '$_logTag _jumpToImageInstant 无效的图片索引: $globalImageIndex，总图片数: ${chapterManager.allImages.length}');
      return;
    }

    print('$_logTag _jumpToImageInstant 跳转到图片，索引: $globalImageIndex');

    // 直接跳转，不使用_isSliderDragging状态
    // 这避免了与进度条状态的冲突
    itemScrollController.jumpTo(
      index: globalImageIndex,
      alignment: 0.0,
    );

    // 更新显示索引，这会触发UI更新
    setState(() {
      _visibleImageIndex = globalImageIndex;
    });

    print(
        '$_logTag _jumpToImageInstant 跳转完成，更新_visibleImageIndex: $_visibleImageIndex');
  }

  void _showChapterList() {
    print(
        '$_logTag _showChapterList 显示章节列表，当前章节: ${chapterManager.displayChapterIndex}，总章节数: ${chapterManager.chapters.length}');
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.black87,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (sharecontext) => ChapterListSheet(
        chapters: chapterManager.chapters,
        displayChapterIndex: chapterManager.displayChapterIndex,
        allImages: chapterManager.allImages,
        onChapterSelected: (index) async {
          print('$_logTag _showChapterList 用户选择章节: $index');
          Navigator.of(sharecontext).pop();
          final chapter = chapterManager.chapters[index];
          if (chapter.isBuy == false) {
            _loadSingleChapter(index);
          } else {
            final isLoggedIn = await UserManager.isLoggedIn();
            if (isLoggedIn) {
              PurchaseBottomSheet.show(
                sharecontext,
                chapterTitle: chapter.chapterTitle ?? "Chapter ${index + 1}",
                chapterPrice:
                    chapterManager.comicDetail?.buyPrice?.chapterPrice ??
                        50, // Replace with actual chapter price
                comicPrice: chapterManager.comicDetail?.buyPrice?.comicPrice ??
                    200, // Replace with actual comic price
                comicTitle:
                    chapterManager.comicDetail?.comic?.title ?? "This Comic",
                onPurchaseChapter: () async {
                  // Handle chapter purchase
                  print('🔥🔥🔥 onPurchaseChapter 被调用了！');
                  // Handle chapter purchase
                  print('Purchase chapter: ${chapter.chapterId}');
                  // Add your chapter purchase logic here
                  EasyLoading.show();
                  try {
                    print('🚀 准备发送HTTP请求...');
                    final response = await HttpUtil().postJson(
                      'ComicMember/BuyComic',
                      data: {"id": chapter.chapterId, "isAllBuyChapter": false},
                    );
                    print("✅ 购买章节接口返回: $response");
                    EasyLoading.dismiss();
                    if (response?['status'] == 200) {
                      EasyLoading.showToast("Purchase completed successfully");
                      // ref
                      //     .read(comicDetailProvider(comicId)
                      //         .notifier)
                      // .refresh();
                      await chapterManager.loadComicDetail(
                          widget.initialChapterId,
                          chapter.chapterId ?? widget.initialChapterId);
                    } else {
                      if (response?['status'] == 400) {
                        _showBalanceInsufficientDialog(context);
                      } else {
                        EasyLoading.showToast(response?['message']);
                      }
                    }
                  } catch (e) {
                    print('❌ 购买请求异常: $e');
                    EasyLoading.dismiss();
                    EasyLoading.showToast("Purchase failed: $e");
                  }
                },
                onPurchaseComic: () async {
                  EasyLoading.show();
                  try {
                    print('🚀 准备发送HTTP请求...');
                    final response = await HttpUtil().postJson(
                      'ComicMember/BuyComic',
                      data: {
                        "id": chapterManager.comicDetail?.comic?.id ?? '',
                        "isAllBuyChapter": true
                      },
                    );
                    print("✅ 购买章节接口返回: $response");
                    EasyLoading.dismiss();
                    if (response?['status'] == 200) {
                      EasyLoading.showToast("Purchase completed successfully");
                      // ref
                      //     .read(comicDetailProvider(comicId)
                      //         .notifier)
                      // .refresh();
                      await chapterManager.loadComicDetail(
                          widget.initialChapterId,
                          chapter.chapterId ?? widget.initialChapterId);
                    } else {
                      if (response?['status'] == 400) {
                        _showBalanceInsufficientDialog(context);
                      } else {
                        EasyLoading.showToast(response?['message']);
                      }
                    }
                  } catch (e) {
                    print('❌ 购买请求异常: $e');
                    EasyLoading.dismiss();
                    EasyLoading.showToast("Purchase failed: $e");
                  }
                },
                onSubscribePremium: () async {
                  await chapterManager.loadComicDetail(widget.initialChapterId,
                      chapter.chapterId ?? widget.initialChapterId);
                },
              );
            } else {
              showDialog(
                context: context,
                barrierDismissible: false,
                builder: (context) => const LoginDialog(),
              );
            }
          }
        },
      ),
    );
  }

  void _showErrorMessage(String message) {
    print('$_logTag _showErrorMessage 显示错误消息: $message');
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        duration: const Duration(seconds: 3),
      ),
    );
  }

  void _toggleAutoReading() {
    print('$_logTag _toggleAutoReading 切换自动阅读状态: ${!_isAutoReading}');
    setState(() {
      _isAutoReading = !_isAutoReading;
    });

    if (_isAutoReading) {
      _startAutoReading();
    } else {
      _stopAutoReading();
    }
  }

  void _startAutoReading() {
    print('$_logTag _startAutoReading 开始自动阅读，当前图片索引: $_visibleImageIndex');
    // 隐藏控制栏
    setState(() {
      _showControls = false;
    });

    // 每50毫秒滚动2像素，实现顺畅的自动滚动
    _autoScrollTimer =
        Timer.periodic(const Duration(milliseconds: 50), (timer) {
      if (!mounted || !_isAutoReading) {
        print('$_logTag _startAutoReading 自动阅读定时器已取消');
        timer.cancel();
        return;
      }

      _performAutoScroll();
    });
  }

  void _stopAutoReading() {
    print('$_logTag _stopAutoReading 停止自动阅读');
    _autoScrollTimer?.cancel();
    _autoScrollTimer = null;

    // 显示控制栏
    setState(() {
      _showControls = true;
    });
  }

  void _performAutoScroll() {
    if (chapterManager.allImages.isEmpty) {
      print('$_logTag _performAutoScroll 图片列表为空，停止自动滚动');
      return;
    }

    // 检查是否已经是最后一张图片
    if (_visibleImageIndex >= chapterManager.allImages.length - 1) {
      // 已经到达最后，停止自动阅读
      print('$_logTag _performAutoScroll 已到达最后一张图片，停止自动阅读');
      _toggleAutoReading();

      // 检查下一章节是否需要付费
      _checkAndHandleNextChapter();
      return;
    }

    scrollOffsetController.animateScroll(
      offset: 10.0,
      duration: const Duration(milliseconds: 100),
      curve: Curves.linear,
    );
  }

  // 新增方法：检查并处理下一章节
  void _checkAndHandleNextChapter() {
    final currentChapterIndex = chapterManager.displayChapterIndex;

    // 检查是否有下一章节
    if (currentChapterIndex < chapterManager.chapters.length - 1) {
      final nextChapterIndex = currentChapterIndex + 1;
      final nextChapter = chapterManager.chapters[nextChapterIndex];

      // 如果下一章节需要付费
      if (nextChapter.isBuy == true) {
        // 下一章节需要付费，弹出购买窗口
        _showPurchaseDialogAfterAutoReading(nextChapterIndex, nextChapter);
      } else {
        // 下一章节免费，显示完成消息并提供继续阅读选项
        // _showContinueReadingOption(nextChapterIndex);
        _loadSingleChapter(nextChapterIndex);
      }
    } else {
      // 已经是最后一章
      _showCompletionMessage();
    }
  }

  // 自动阅读结束后显示购买窗口
  void _showPurchaseDialogAfterAutoReading(
      int nextChapterIndex, dynamic nextChapter) {
    print('$_logTag 自动阅读结束，下一章节需要付费，显示购买窗口');

    // 延迟一下再显示，让用户感知到阅读已结束
    Future.delayed(const Duration(milliseconds: 500), () {
      if (!mounted) return;

      PurchaseBottomSheet.show(
        context,
        chapterTitle:
            nextChapter.chapterTitle ?? "Chapter ${nextChapterIndex + 1}",
        chapterPrice: chapterManager.comicDetail?.buyPrice?.chapterPrice ?? 50,
        comicPrice: chapterManager.comicDetail?.buyPrice?.comicPrice ?? 200,
        comicTitle: chapterManager.comicDetail?.comic?.title ?? "This Comic",
        onPurchaseChapter: () async {
          print('🔥 自动阅读后购买章节: ${nextChapter.chapterId}');
          EasyLoading.show();
          try {
            final response = await HttpUtil().postJson(
              'ComicMember/BuyComic',
              data: {"id": nextChapter.chapterId, "isAllBuyChapter": false},
            );
            print("✅ 购买章节接口返回: $response");
            EasyLoading.dismiss();

            if (response?['status'] == 200) {
              EasyLoading.showToast("Purchase completed successfully");
              // 购买成功后自动跳转到下一章节
              _loadSingleChapter(nextChapterIndex);
              // 可选：重新开始自动阅读
              Future.delayed(const Duration(milliseconds: 1000), () {
                if (mounted && !_isAutoReading) {
                  _toggleAutoReading();
                }
              });
            } else {
              if (response?['status'] == 400) {
                _showBalanceInsufficientDialog(context);
              } else {
                EasyLoading.showToast(response?['message']);
              }
            }
          } catch (e) {
            print('❌ 购买请求异常: $e');
            EasyLoading.dismiss();
            EasyLoading.showToast("Purchase failed: $e");
          }
        },
        onPurchaseComic: () async {
          // 购买整部漫画的逻辑
          EasyLoading.show();
          try {
            final response = await HttpUtil().postJson(
              'ComicMember/BuyComic',
              data: {
                "id": chapterManager.comicDetail?.comic?.id ?? '',
                "isAllBuyChapter": true
              },
            );
            EasyLoading.dismiss();

            if (response?['status'] == 200) {
              EasyLoading.showToast("Purchase completed successfully");
              _loadSingleChapter(nextChapterIndex);
              // 重新开始自动阅读
              Future.delayed(const Duration(milliseconds: 1000), () {
                if (mounted && !_isAutoReading) {
                  _toggleAutoReading();
                }
              });
            } else {
              if (response?['status'] == 400) {
                _showBalanceInsufficientDialog(context);
              } else {
                EasyLoading.showToast(response?['message']);
              }
            }
          } catch (e) {
            print('❌ 购买请求异常: $e');
            EasyLoading.dismiss();
            EasyLoading.showToast("Purchase failed: $e");
          }
        },
        onSubscribePremium: () {
          print('Subscribe to premium');
          _loadSingleChapter(nextChapterIndex);
          // 重新开始自动阅读
          Future.delayed(const Duration(milliseconds: 1000), () {
            if (mounted && !_isAutoReading) {
              _toggleAutoReading();
            }
          });
        },
      );
    });
  }

  // 显示继续阅读选项（下一章节免费时）
  void _showContinueReadingOption(int nextChapterIndex) {
    print('$_logTag 自动阅读结束，下一章节免费，显示继续选项');

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Row(
          children: [
            Icon(Icons.auto_stories, color: Colors.white, size: 20),
            SizedBox(width: 8),
            Text('Auto reading completed. Continue to next chapter?'),
          ],
        ),
        backgroundColor: const Color(0xFF8A2BE2),
        duration: const Duration(seconds: 5),
        action: SnackBarAction(
          label: 'Continue',
          textColor: Colors.white,
          onPressed: () {
            print('$_logTag 点击继续阅读下一章节');
            _loadSingleChapter(nextChapterIndex);
            // 延迟后重新开始自动阅读
            Future.delayed(const Duration(milliseconds: 1000), () {
              if (mounted && !_isAutoReading) {
                _toggleAutoReading();
              }
            });
          },
        ),
      ),
    );
  }

  void _showCompletionMessage() {
    print('$_logTag _showCompletionMessage 显示自动阅读完成消息');
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Row(
          children: [
            Icon(Icons.check_circle, color: Colors.white, size: 20),
            SizedBox(width: 8),
            Text('Auto reading completed'),
          ],
        ),
        backgroundColor: const Color(0xFF8A2BE2),
        duration: const Duration(seconds: 3),
        action: SnackBarAction(
          label: 'Start over',
          textColor: Colors.white,
          onPressed: () {
            print('$_logTag _showCompletionMessage 点击重新开始自动阅读');
            _jumpToImageInstant(0);
            Future.delayed(const Duration(milliseconds: 500), () {
              _toggleAutoReading();
            });
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: _isInitializing
          ? const Center(
              child: CircularProgressIndicator(color: Colors.white),
            )
          : Stack(
              children: [
                GestureDetector(
                  onTap: () {
                    print(
                        '$_logTag build 用户点击屏幕，自动阅读状态: $_isAutoReading，控制栏显示: $_showControls');

                    if (_isAutoReading) {
                      _toggleAutoReading();
                    } else {
                      setState(() {
                        _showControls = !_showControls;
                      });
                      print('$_logTag build 切换控制栏显示状态: $_showControls');
                    }
                  },
                  child: ImageListView(
                    images: chapterManager.allImages,
                    isLoadingNext: _isLoadingNext,
                    itemScrollController: itemScrollController,
                    scrollOffsetController: scrollOffsetController,
                    itemPositionsListener: itemPositionsListener,
                    onRefresh: _onRefresh,
                  ),
                ),

                // 顶部控制栏
                if (_showControls)
                  Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    child: ReaderTopControls(
                      chapterTitle: chapterManager.displayChapterIndex <
                              chapterManager.chapters.length
                          ? chapterManager
                                  .chapters[chapterManager.displayChapterIndex]
                                  .chapterTitle ??
                              '​​Unknown chapter​'
                          : '​​Unknown chapter​',
                      onBack: () => Navigator.of(context).pop(),
                      onMore: () {
                        showModalBottomSheet(
                          context: context,
                          // Remove default rounded corners and shadow
                          backgroundColor: Colors.transparent,
                          // Allow full screen height
                          isScrollControlled: true,
                          // Animation transition
                          transitionAnimationController: AnimationController(
                            vsync: Navigator.of(context),
                            duration: const Duration(milliseconds: 300),
                          ),
                          builder: (context) => const ReportSheetContent(),
                        );
                      },
                      onTitleTap: () {
                        // 点击标题跳转到详情页
                        final comicId = chapterManager.comicDetail?.comic?.id;
                        if (comicId != null) {
                          context.pushNamed('home_detail',
                              pathParameters: {'comicId': comicId});
                        }
                      },
                    ),
                  ),

                // 底部控制栏
                if (_showControls)
                  Positioned(
                    bottom: 0,
                    left: 0,
                    right: 0,
                    child: Builder(
                      builder: (context) {
                        final position = chapterManager
                            .getCurrentChapterPosition(_visibleImageIndex);
                        final currentImageInChapter =
                            position['imageInChapter']!;
                        final totalInChapter = position['totalInChapter']!;

                        if (!_isSliderDragging) {
                          _sliderValue = currentImageInChapter.toDouble();
                        }

                        return ReaderBottomControls(
                          imageInChapter: _isSliderDragging
                              ? _sliderValue.round()
                              : currentImageInChapter,
                          totalInChapter: totalInChapter,
                          sliderValue: _sliderValue,
                          canGoPrevious: chapterManager.displayChapterIndex > 0,
                          canGoNext: chapterManager.displayChapterIndex <
                              chapterManager.chapters.length - 1,
                          isAutoReading: _isAutoReading,
                          onSliderChanged: (value) {
                            setState(() {
                              _sliderValue = value;
                            });
                          },
                          onSliderChangeStart: (value) {
                            print(
                                '$_logTag build 开始拖拽进度条，值: $value，自动阅读状态: $_isAutoReading');
                            // 拖拽进度条时暂停自动阅读
                            if (_isAutoReading) {
                              _toggleAutoReading();
                            }
                            setState(() {
                              _isSliderDragging = true;
                              _sliderValue = value;
                            });
                          },
                          onSliderChangeEnd: (value) {
                            print(
                                '$_logTag build 结束拖拽进度条，最终值: $value，跳转到图片: ${value.round()}');
                            setState(() {
                              _sliderValue = value;
                              _isSliderDragging = false;
                            });
                            _jumpToImageInCurrentChapterInstant(value.round());
                          },
                          onPreviousChapter: _goToPreviousChapter,
                          onNextChapter: _goToNextChapter,
                          onShowChapterList: _showChapterList,
                          onToggleAutoReading: _toggleAutoReading,
                        );
                      },
                    ),
                  ),
              ],
            ),
    );
  }

  void _showBalanceInsufficientDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        child: Container(
          width: MediaQuery.of(context).size.width * 0.85,
          decoration: BoxDecoration(
            gradient: const LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Color(0xFF2D1B69),
                Color(0xFF1A0E3D),
              ],
            ),
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                blurRadius: 20,
                offset: const Offset(0, 10),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // Header
              Container(
                padding: const EdgeInsets.all(24),
                child: Column(
                  children: [
                    Icon(
                      Icons.account_balance_wallet_outlined,
                      color: Colors.amber,
                      size: 56,
                    ),
                    const SizedBox(height: 16),
                    Text(
                      'Insufficient Balance',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 26,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 12),
                    Text(
                      'You don\'t have enough coins to purchase this chapter. Please top up your account to continue reading.',
                      style: TextStyle(
                        color: Colors.white70,
                        fontSize: 15,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),

              // Action Buttons
              Padding(
                padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
                child: Column(
                  children: [
                    // Top Up Button
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton.icon(
                        onPressed: () {
                          Navigator.of(context).pop();
                          // Navigate to top up screen
                          context.push('/topup');
                        },
                        icon: const Icon(Icons.add_circle_outline,
                            color: Colors.white),
                        label: const Text(
                          'Top Up Coins',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Color(0xFF4CAF50),
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                          elevation: 4,
                        ),
                      ),
                    ),

                    const SizedBox(height: 12),

                    // Go Premium Button
                    SizedBox(
                      width: double.infinity,
                      child: OutlinedButton.icon(
                        onPressed: () {
                          Navigator.of(context).pop();
                          // Navigate to premium screen
                          GoRouter.of(context).pushNamed('PremiumScreen');
                        },
                        icon: const Icon(Icons.workspace_premium,
                            color: Colors.amber),
                        label: const Text(
                          'Go Premium',
                          style: TextStyle(
                            color: Colors.amber,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        style: OutlinedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          side: BorderSide(color: Colors.amber, width: 2),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              // Close Button
              Padding(
                padding: const EdgeInsets.fromLTRB(24, 0, 24, 16),
                child: TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: Text(
                    'Maybe Later',
                    style: TextStyle(
                      color: Colors.white60,
                      fontSize: 15,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
